var APP = {
	base: '',
	onLoad: ''
};

window.addEvent('domready', function(){
	APP.onLoad();
});

var ADD_HANDLER = {
	onLoad_add: function (){
		var dtp = $$('.datepicker');
		var tmp = [];
		
		//datepicker
		dtp.each(function(item, index){
			var opt = {timePicker:true, inputOutputFormat:'Y-m-d H:i:s', format:'d-F-Y H:i:s'};
			if (index>0) opt = $merge(opt, {maxDate:{date:tmp[index-1].attachTo.value, format:'Y-m-d'},onClose:$empty})
			tmp[index] = dtpicker_attach0(item, opt);
		});
		
		tmp[0].options.onClose = function(){
			tmp[1].options.maxDate = {date:tmp[0].attachTo.value, format:'Y-m-d'};
			if (tmp[1].attachTo) tmp[1].attachTo.value = '' ;
			if (tmp[1].visual) tmp[1].visual.value =  '';
		}
		
		$('tpl_pelapor').addEvent('click', function(){
			ADD_HANDLER._actionListener_searchPelapor();
			ADD_HANDLER._actionListener_searchPelapor_button = this;
		});
		
		$('tpl_kary3').addEvent('click', function(){
			ADD_HANDLER._actionListener_searchKary();
			ADD_HANDLER._actionListener_searchKary_button = this;
		});
		
		$('tpl_kategoriButton').addEvent('click', function(){
			ADD_HANDLER._actionListener_searchPerbuatan();
			ADD_HANDLER._actionListener_searchPerbuatan_button = this;
		});
		
		//upload
		var checkBox= {class:"uploadFile validate['group[1,1]']",type: 'checkbox', 'checked': true};
		var upload = upload_attach({
			list: 'fcUpload-list', 
			button: '#fcUpload-attach, #fcUpload-attach-2', 
			path: APP.base.replace('psdm/perbuatan','js/Swiff.Uploader.swf'),
			url: APP.base.replace('psdm/perbuatan','uploadListener.php'),
			imageUrl: APP.base.replace('psdm/perbuatan','img/FancyUpload'),
			onFileSuccess: function(file, res) {
				var json = JSON.decode(res);
				if (json.error){
					upload.onFileSuccess(file);
				}
				else if (!json.error){
					var ch = new Element('input', $merge(checkBox,{name:'inp[9][]',value:json.name}))
						.inject(file.ui.element, 'top');
					file.ui.element.highlight('#e6efc2');
					APP.formCheck.register(ch);
				}
				
				//destroy the first button
				var ubt = $('fcUpload-check');
				if (ubt){
					APP.formCheck.dispose(ubt);
					ubt.destroy();
				}
			}
		});
		
		//install formcheck
		APP.formCheck = new FormCheck('frmModal',{submitByAjax:true, validateDisabled:true,
	        onAjaxSuccess: function(res){
				var json = JSON.decode(res);
				FBModal_message(APP.base+'/ajax/messageDialog', "Save", json.msg);
				if (json.location && !json.error) document.location = json.location;
	        }
	    });
	},
	_actionListener_searchPelapor: function(){
		var utils = APP.base.replace('/psdm/perbuatan','/utils/searchDialog/pelapor/getDialog');
		FBModal_show2(utils, 'post', 
			"submit_action=ADD_HANDLER._actionListener_searchPelapor_pick"+
			"&return_fields=lapor_id,lapor_nama"+
			"&where=lapor_nik=''"+
			"&translate=true", 
			true, false, null, {
			onSuccess: function(res){
				Utils.searchDialog.install({
					form:'pelaporSearchFrm',
					pagination:'pelaporSearchFrm_pagination',
					table: {
						element:'pelaporSearchFrm_table',
						columns:['lapor_id','lapor_nama', 'lapor_nik'],
						content:'pelaporSearchFrm_tableContent'
					}
				});
			}
		});
	},
	_actionListener_searchPelapor_pick: function(id, name){
		$$('input[name="inp[0][0]"]')[0].value = $chk(id)? id : '';
		$$('input[name="inp[0][1]"]')[0].value = $chk(name)? name : '';
		$$('input[name="inp[0][1]"]')[0].disabled = $chk(id);
		
		//we need to avoid formCheck untuk alamat dan tlp, isi dengan nilai sembarang
		var i=0;
		$$($$('input[name^="inp[1]"]'), $$('select[name^="inp[1]"]'), 
		   $$('input[name^="inp[2]"]')).each(function(item){
			if (item.type=='text') item.value= $chk(id)? i++ : '';
			if (item.get('tag')=='select') item.selectedIndex= $chk(id)? 1 : 0;
		});
		$('noPelaporID').setStyle('display',$chk(id)?'none':'table-row-group');
		$('yesPelaporID').setStyle('display',$chk(id)?'table-row':'none');
		
		//no id, bail...
		if (!$chk(id)) {
			
		}
		//there is an ID, load the alamat and tlp
		else{
			
		}
		
		FBModal_hide();
	},
	_actionListener_searchPelapor_button: null,
	
	_actionListener_searchPerbuatan: function(){
		var utils = APP.base.replace('/psdm/perbuatan','/utils/searchDialog/detachievement/getDialog');
		FBModal_show2(utils, 'post', 
			"submit_action=ADD_HANDLER._actionListener_searchPerbuatan_pick"+
			"&return_fields=detachiev_id,detachiev_nama,achiev_jenis,achiev_bidang,detachiev_tingkat"+
			"&translate=true", 
			true, false, null, {
			onSuccess: function(res){
				Utils.searchDialog.install({
					form:'detachievSearchFrm',
					pagination:'detachievSearchFrm_pagination',
					table: {
						element:'detachievSearchFrm_table',
						columns:['detachiev_id','detachiev_nama', 'detachiev_tingkat', 'achiev_jenis','achiev_bidang'],
						content:'detachievSearchFrm_tableContent'
					}
				});
			}
		});
	},
	_actionListener_searchPerbuatan_pick: function(id, nama, jenis, bidang, tingkat){
		var button = ADD_HANDLER._actionListener_searchPerbuatan_button;
		var inp = button.getParent('tr').getElements('input'); 
		var innerTable = button.getParent('td').getElement('table');
		inp.each(function(item, index){
			if (index==0) item.value=id;
			if (index==1) item.value=nama;
		});
		
		var ee = [jenis, bidang, tingkat];
		innerTable.setStyle('display','table').getElements('td').each(function(item, index){
			if (index % 2==1){
				item.set('html',ee[parseInt(index/2)]);
			}
		});
		FBModal_hide();
	},
	_actionListener_searchPerbuatan_button: null,
	
	_actionListener_searchKary: function(){
		var ww = "";
		$$("input[name^='inp[7]']").each(function(item){
			ww += (ww? "," :"")+"'"+item.value+"'";
		});
		var utils = APP.base.replace('/psdm/perbuatan','/utils/searchDialog/karyawan/getDialog');
		FBModal_show2(utils, 'post', 
			"submit_action=ADD_HANDLER._actionListener_searchKary_pick"+
			"&where= kary_id NOT IN ("+ww+")", true, false, null, {
			onSuccess: function(res){
				Utils.searchDialog.install({
					form:'karyawanSearchFrm',
					pagination:'karyawanSearchFrm_pagination',
					table: {
						element:'karyawanSearchFrm_table',
						columns:['kary_id','kary_nama','kary_status_marital','kary_email','kary_tgl_masuk'],
						content:'karyawanSearchFrm_tableContent',
					}
				});
			}
		});
	},
	_actionListener_searchKary_pick: function(id, name){
		//get container
		var tr = ADD_HANDLER._actionListener_searchKary_button.getParent('tr');
		
		tr.getElements('input').each(function(item){
			if (item.type=='text') item.set('value', name);
			if (item.type=='hidden') item.set('value', id);
		});
		
		//determine the select name
		var inp = tr.getElements('input[name^="inp[7]"]');
		inp_name = inp[0].name.replace('inp[7][','').replace(']','').toInt();

		//create the element
		var old = $$("select[name='inp[7]["+(inp_name+1)+"]']")[0];
		var jbt = $chk(old)? old : new Element('select',{style:'margin-left:5px',
			class:"validate['required']", name:'inp[7]['+(++inp_name)+']'});
		jbt.empty().grab(new Element('option',{html:'--- pilih ---'}))
			.inject(ADD_HANDLER._actionListener_searchKary_button, 'before');
		APP.formCheck.register(jbt, inp[0].getParent('tr').getElement('input'));

		ajax(APP.base+'/ajax/getJabatanCombo/'+id, 'post', "", $empty, 
			function(res){
				this.set('html', this.get('html')+res);
			}.bind(jbt));
		FBModal_hide();
	},
	_actionListener_searchKary_button: null,
	
	more_alm_counter: 1,
	more_alm: function(button){
		var tr = new Element('tr');
		var td1= new Element('td', {style:'width="40%" valign="top"'});
		var td2= new Element('td');
		var td3= new Element('td');
		
		var a = new Element('a',{html:'delete',style:'margin-left:10px', class:'fakeLink'}).addEvent('click',function(){
			ADD_HANDLER._destroy_alamat_row(this.getParent('tr'));
		})

		var dd = $('tpl_alm1').clone().set('value','')
			.set('name', 'inp[1]['+ (++this.more_alm_counter) + ']')
			.set('class','')
			.set('class', $('tpl_alm1').get('class').replace(/\]/i,",'%differsAlm']"));
		var ee = $('tpl_alm2').clone();
		ee.set('name', 'inp[1]['+ (++this.more_alm_counter) + ']').selectedIndex=0;
		
		td1.inject(tr);
		td2.grab(dd).inject(tr);
		td3.grab(ee).grab(a).inject(tr);
		
		tr.inject(button.getParent('tr'), 'before');
		
		//register
		var prev = $$("select[name='inp[1]["+ (this.more_alm_counter-2) +"]']")[0];
		APP.formCheck.register(dd,prev).register(ee,dd);
	},
	more_tlp_counter: 1,
	more_tlp: function(button){
		var tr = new Element('tr');
		var td1= new Element('td');
		var td2= new Element('td');
		var a = new Element('a',{html:'delete',style:'margin-left:10px', class:'fakeLink'}).addEvent('click',function(){
			ADD_Handler._destroy_tlp_row(this.getParent('tr'));
		})
		
		var dd = $('tpl_tlp1').clone().set('value','').set('name','inp[2]['+ (++this.more_tlp_counter) +']');
		var ee =$('tpl_tlp2').clone()
			.set('value','').set('name','inp[2]['+ (++this.more_tlp_counter) +']')
			.set('class','')
			.set('class', $('tpl_tlp2').get('class').replace(/\]/i,",'%differsTlp']"));
		
		td1.inject(tr);
		td2.grab(dd).appendText(' - ').grab(ee).grab(a).inject(tr);
		
		tr.inject(button.getParent('tr'), 'before');
		
		//register
		var prev = $$("input[name='inp[2]["+ (this.more_tlp_counter-2) +"]']")[0];
		APP.formCheck.register(dd, prev).register(ee, dd);
	},
	more_kary_counter: 1,
	more_kary: function(button){
		var tr = new Element('tr');
		var td = new Element('td');
		
		var dd = $('tpl_kary1').clone().set('value','');
		var ee = $('tpl_kary2').clone().set('name',"inp[7]["+ (++this.more_kary_counter) +"]").set('value','');
		var ff = $('tpl_kary3').clone().cloneEvents($('tpl_kary3'),'click');
		var gg = new Element('a',{html:'delete',style:'margin-left:10px', class:'fakeLink'}).addEvent('click',function(){
			ADD_HANDLER._destroy_kary_row(this.getParent('tr'));
		})
		
		td.grab(dd).grab(ee).grab(ff).grab(gg).inject(tr);
		tr.grab(new Element('td')).grab(td).inject(button.getParent('tr'),'before');
		
		++this.more_kary_counter; //add gap
		
		//register
		var prev = $$("select[name='inp[7]["+ (this.more_kary_counter-2) +"]']")[0];
		prev = $chk(prev)? prev : $$("input[name='inp[7]["+ (this.more_kary_counter-3) +"]']")[0].getParent('tr').getElement('input');
		APP.formCheck.register(dd,prev);
	},
	
	_destroy_alamat_row:function(tr){
		$$(tr.getElements("input[name^='inp[1]']"), tr.getElements("select[name^='inp[1]']")).each(function(item){
			APP.formCheck.dispose(item);
		});
		tr.destroy();
		this.more_alm_counter -=2;
	},
	_destroy_tlp_row:function(tr){
		tr.getElements('input[name^="inp[2]"]').each(function(item){
			APP.formCheck.dispose(item);
		});
		tr.destroy();
		this.more_tlp_counter -=2;
	},
	_destroy_kary_row:function(tr){
		$$(tr.getElements('input[name^="inp[7]"]'), tr.getElements('select[name^="inp[7]"]')).each(function(item){
			APP.formCheck.dispose(item);
		});
		tr.destroy();
		ADD_HANDLER.more_kary_counter -= ADD_HANDLER.more_kary_counter-2%2==0? 1 : 2;
	}
}

function differsAlm(el){
	var valid = true;
	$$("input[name^='inp[1]']").each(function(item, index){
		if (index%2==0 && item != el && el.value==item.value){
			el.errors.push("This value must be different of the others Address");
			valid = false;
		}
	});
	return valid;
}

function differsTlp(el){
	var valid = true;
	$$("input[name^='inp[2]']").each(function(item, index){
		if (index%2==1 && item != el && el.value==item.value){
			el.errors.push("This value must be different of the others phone number");
			valid = false;
		}
	});
	return valid;
}